package com.example.service.Impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.context.BaseContext;
import com.example.mapper.NoticeMapper;
import com.example.pojo.entity.Account;
import com.example.pojo.entity.Admin;
import com.example.pojo.entity.Notice;
import com.example.service.AdminService;
import com.example.service.NoticeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.List;

/**
 * 公告信息表业务处理
 **/
@Service
@DS("master")
public class NoticeServiceImpl extends ServiceImpl<NoticeMapper,Notice> implements NoticeService {

    @Resource
    private NoticeMapper noticeMapper;

    @Autowired
    private AdminService adminService;

    /**
     * 新增
     */
    public void add(Notice notice) {
        notice.setDatetime(LocalDate.now());
        Admin admin = adminService.selectById(Math.toIntExact(BaseContext.getCurrentId()));
        notice.setUser(admin.getUsername());
        notice.setIsDeleted(0);
        notice.setVersion(0);
        noticeMapper.insert(notice);
    }

    /**
     * 删除
     */
    public void deleteById(Integer id) {
        Notice notice = selectById(id);
        notice.setIsDeleted(1);
        noticeMapper.updateById(notice);
    }

    /**
     * 批量删除
     */
    public void deleteBatch(List<Integer> ids) {
        for (Integer id : ids) {
            Notice notice = selectById(id);
            notice.setIsDeleted(1);
            noticeMapper.updateById(notice);
        }
    }

    /**
     * 根据ID查询
     */
    public Notice selectById(Integer id) {
        return noticeMapper.selectById(id);
    }

    /**
     * 分页查询
     */
    public Page<Notice> selectPage(String title, Integer pageNum, Integer pageSize) {
        QueryWrapper<Notice> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StrUtil.isNotBlank(title),"title",title);
        queryWrapper.eq("is_deleted",0);
        return noticeMapper.selectPage(new Page<>(pageNum, pageSize), queryWrapper);
    }

}
